package com.eight.cloud.mybatisplus.datascope.expression;

import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.core.global.constant.DataScopeConstants;
import com.eight.cloud.core.global.model.DataScopeModel;
import com.eight.cloud.core.global.model.BaseUser;
import com.eight.cloud.mybatisplus.datascope.SqlWhereExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList;
import net.sf.jsqlparser.schema.Column;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门级数据权限
 *
 * @ClassName: DeptExpression
 * @Author: TXC
 * @Date: 2025-06-11 17:02
 **/
@Component
public class DeptExpression implements SqlWhereExpression {
    @Override
    public Expression getExpression(Column column, BaseUser currentUser, DataScopeModel dataScopeModel) {
        List<String> deptIdList = dataScopeModel.getDeptIds();
        if (ObjectUtil.isNotNull(deptIdList)) {
            // 构造部门eq表达式
            ExpressionList<StringValue> deptIds = new ParenthesedExpressionList<>(deptIdList.stream().map(StringValue::new).collect(Collectors.toList()));
            return new InExpression(column, deptIds);
        }
        return null;
    }

    @Override
    public boolean isSupport(DataScopeModel dataScopeModel) {
        return !dataScopeModel.getDataScope().equals(DataScopeConstants.DATA_SCOPE_ALL)
                && !dataScopeModel.getDataScope().equals(DataScopeConstants.DATA_SCOPE_SELF);
    }

}
